package com.xhtt.modules.app.controller.task;

import com.xhtt.common.exception.RRException;
import com.xhtt.common.exception.RRExceptionEnum;
import com.xhtt.common.utils.*;
import com.xhtt.common.validator.ValidatorUtils;
import com.xhtt.modules.app.annotation.Login;
import com.xhtt.modules.app.annotation.LoginUser;
import com.xhtt.modules.sys.controller.AbstractController;
import com.xhtt.modules.sys.entity.SysUserEntity;
import com.xhtt.modules.task.entity.SuperTaskUser;
import com.xhtt.modules.task.model.alltask.*;
import com.xhtt.modules.task.service.TaskAllService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * app操作全部任务的接口
 * </p>
 *
 * @author feipc
 * @since 2019-02-26
 */
@Api(tags = "计划任务-app操作全部任务的接口", value = "计划任务-app操作全部任务的接口")
@RestController
@RequestMapping("app/task/all")
public class TaskAllController extends AbstractController {

    @Autowired
    private TaskAllService taskAllService;

    /**
     * 操作任务数量
     */
    @GetMapping(value = "/allTaskCount")
    @ApiOperation("操作任务数量(app)")
    @Login
    public R allTaskCount(@ApiIgnore @LoginUser SysUserEntity user, @RequestParam Integer status) {
        int count = taskAllService.allTaskCount(user, status);
        return R.ok().put(Constant.DATA, count);
    }

    /**
     * 操作任务列表
     */
    @GetMapping(value = "/allTaskList")
    @ApiOperation("操作任务列表(app)")
    @Login
    public R allTaskList(@ApiIgnore @LoginUser SysUserEntity user, @RequestParam Integer status) {
        List<TaskAllModel> list = taskAllService.allTaskList(user, status);
        return R.ok().put(Constant.DATA, list);
    }

    /**
     * 协助任务数量
     */
    @GetMapping(value = "/assistTaskCount")
    @ApiOperation("协助任务数量(app)")
    @Login
    public R assistTaskCount(@ApiIgnore @LoginUser SysUserEntity user) {
        int count = taskAllService.assistTaskCount(user);
        return R.ok().put(Constant.DATA, count);
    }

    /**
     * 协助任务列表
     */
    @GetMapping(value = "/assistTaskList")
    @ApiOperation("协助任务列表(app)")
    @Login
    public R assistTaskList(@ApiIgnore @LoginUser SysUserEntity user) {
        List<TaskAllModel> list = taskAllService.assistTaskList(user);
        return R.ok().put(Constant.DATA, list);
    }


    /**
     * 交接班
     */
    @ApiOperation("交接班(app)")
    @PostMapping("/changeShifts")
    @Login
    public R changeShifts(@RequestBody SuperTaskUser carTaskUser, @ApiIgnore @LoginUser SysUserEntity user) {
        // 把自己没完成的任务分给别人啦
        taskAllService.changeShifts(user, carTaskUser);

        return R.ok();
    }

    /**
     * 交接班-组长把任务分给别的组（任务换组，确认人还要换 fuck，本质上就是把消息给别人）
     */
    @ApiOperation("交接班-组长把任务分给别的组(app)")
    @PostMapping("/arrangeTeam")
    @Login
    public R arrangeTeam(@RequestBody ArrangeTeamModel model, @ApiIgnore @LoginUser SysUserEntity user) {
        taskAllService.arrangeTeam(user, model);

        return R.ok();
    }

    /**
     * 交接班-组长把任务分给人员
     */
    @ApiOperation("交接班-组长把任务分给人员(app)")
    @PostMapping("/arrangeUser")
    @Login
    public R arrangeUser(@RequestBody ArrangeUserModel model, @ApiIgnore @LoginUser SysUserEntity user) {
        ValidatorUtils.validateEntity(model);
        taskAllService.arrangeUser(user, model);

        return R.ok();
    }

    /**
     * 核心任务列表
     */
    @ApiOperation("核心任务列表-计划任务(web)")
    @GetMapping("/corePlanList")
    @Login
    public R corePlanList(@RequestParam Map<String, Object> params) {
        PageUtils page = taskAllService.corePlanList(params);
        return R.ok().put(Constant.DATA, page);
    }

    @GetMapping(value = "/export")
    @ApiOperation("核心任务列表导出")
    @Login
    public void export(HttpServletResponse response, @RequestParam Map<String, Object> params) {
        ExportExcel exportExcel = new ExportExcel();
        params.put("limit", "65000");
        PageUtils page = taskAllService.corePlanList(params);
        List<TaskPlanAllModel> list = (List<TaskPlanAllModel>) page.getList();
        //转化一下
        List<ExcelTaskAllModel> el = change(list);
        String fileName = "核心任务表-计划任务";
        String sheetName = "计划任务";
        String[] headers = {"任务模块", "任务类型", "任务名称", "班组人员", "完成进度", "分支任务", "计划开始时间", "状态"};
        String[] columns = {"plan", "planTypeName", "planTaskName", "team_user", "percentName", "task_percent", "planStartDateName", "statusName"};
        try {
            exportExcel.exportExcel(fileName, sheetName, headers, columns, el, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException(RRExceptionEnum.EXPORT_FAIL);
        }

    }

    private List<ExcelTaskAllModel> change(List<TaskPlanAllModel> list) {
        List<ExcelTaskAllModel> ml = new ArrayList<>();
        ExcelTaskAllModel m;
        for (TaskPlanAllModel am : list) {
            m = new ExcelTaskAllModel();
            CopyUtils.copyProperties(am, m);
            List<TeamUserModel> userModelList = am.getUserModelList();
            StringBuffer sb = new StringBuffer();
            for (TeamUserModel um : userModelList) {
                sb.append(null == um.getTeamName() ? StringUtils.EMPTY : um.getTeamName()).append("-").append(null == um.getUserName() ? StringUtils.EMPTY : um.getUserName()).append("\r\n");
            }
            m.setTeam_user(sb.toString());

            List<SubTaskModel> subTaskModelList = am.getSubTaskModelList();
            sb = new StringBuffer();
            for (SubTaskModel tm : subTaskModelList) {
                sb.append(tm.getTaskName() + " " + tm.getFinishStatus() + "%\r\n");
            }
            m.setTask_percent(sb.toString());

            ml.add(m);
        }
        return ml;
    }
}
